#ifndef CONFIGMANAGER_H
#define CONFIGMANAGER_H

#include <QMutex>
#include <QString>
#include <exception>  // 使用标准异常库

// 串口配置参数结构体
struct SerialConfig {
    QString portName;
    int baudRate;
    int dataBits;
    int parity;
    int stopBits;
    QString flowControl;
};

// 配置管理类（单例模式）
class ConfigManager
{
public:
    static ConfigManager* getInstance();
    void setConfig(const SerialConfig &config);
    void setFile(const QString &fileName);
    SerialConfig load();  // 返回串口配置参数
    bool saveAs(const QString &fileName);
    bool save();


private:
    explicit ConfigManager() noexcept = default;
    ~ConfigManager() noexcept = default;
    ConfigManager(const ConfigManager&) = delete;
    ConfigManager& operator=(const ConfigManager&) = delete;

    QString m_configFile;
    SerialConfig m_currentConfig;
    static QAtomicPointer<ConfigManager> m_instance;
    static QMutex mutex;
};

// 自定义异常类，继承 std::exception
class ConfigManagerException : public std::exception
{
public:
    ConfigManagerException(const QString &errMsg, const QString &errReason)
        : _errMsg(errMsg), _errReason(errReason) {}

    ~ConfigManagerException() noexcept override = default;

    // 重写 what() 函数，返回详细的异常信息
    const char* what() const noexcept override {
        QString message = QString("Error: %1, Reason: %2").arg(_errMsg).arg(_errReason);
        // 注意：必须将 QString 转换为 std::string 再转换为 const char*
        return message.toStdString().c_str();
    }

private:
    QString _errMsg;     // 错误消息
    QString _errReason;  // 错误原因
};

#endif // CONFIGMANAGER_H
